#include "LPTIM32.h"

LPTIM32_InfoTypeDef LPTIM32_Info = {0};
/*

*/
void LPTIM_IRQHandler(void)
{
    if(FL_LPTIM32_IsEnabledIT_Update(LPTIM32) && FL_LPTIM32_IsActiveFlag_Update(LPTIM32))
    {
        FL_LPTIM32_ClearFlag_Update(LPTIM32);
		LPTIM32_Info.MsCount++;
		LPTIM32_Info.Flag.Bit.MsFlag = 1;
    }
}

void LPTIM32_InitConfig(void)
{
    FL_LPTIM32_InitTypeDef FL_LPTIM32_InitStruct;

    FL_LPTIM32_InitStruct.clockSource = FL_RCC_LPTIM32_CLK_SOURCE_APB1CLK;
    FL_LPTIM32_InitStruct.prescalerClockSource = FL_LPTIM32_CLK_SOURCE_INTERNAL;
    FL_LPTIM32_InitStruct.prescaler = FL_LPTIM32_PSC_DIV8;
    FL_LPTIM32_InitStruct.autoReload = 1000;
    FL_LPTIM32_InitStruct.mode = FL_LPTIM32_OPERATION_MODE_NORMAL;
    FL_LPTIM32_InitStruct.onePulseMode = FL_LPTIM32_ONE_PULSE_MODE_CONTINUOUS;
    FL_LPTIM32_InitStruct.countEdge = FL_LPTIM32_ETR_COUNT_EDGE_RISING;
    FL_LPTIM32_InitStruct.triggerEdge = FL_LPTIM32_ETR_TRIGGER_EDGE_RISING;

    FL_LPTIM32_Init(LPTIM32, &FL_LPTIM32_InitStruct);

    FL_LPTIM32_EnableIT_Update(LPTIM32);
}

void LPTIM32_NVIC_InitConfig(void)
{
	FL_NVIC_ConfigTypeDef InterruptConfigStruct;
	InterruptConfigStruct.preemptPriority = 0x03;
	FL_NVIC_Init(&InterruptConfigStruct, LPTIM_IRQn);
}

void LPTIM32_Control(LPTIM32_RunStateTypeDef state)
{
	if(state == LPTIM32_RUNSTART){
		SET_BIT(LPTIM32->CR, LPTIM32_CR_EN_Msk);
	}
	else if(state == LPTIM32_RUNSTOP){
		CLEAR_BIT(LPTIM32->CR, LPTIM32_CR_EN_Msk);
	}	
}

uint32_t CalculateInterval(uint32_t current_tick, uint32_t previous_tick)
{
    return (current_tick >= previous_tick) ? (current_tick - previous_tick) : (SYSTEM_COUNTER_MAX - previous_tick + current_tick + 1);
}
